// pages/createOrder/createOrder.js
const request = require('../../utils/request');
const { getUserLocation } = require('../../utils/location');

const ITEM_TYPE_OPTIONS = [
  { label: '快递包裹', value: 'express' },
  { label: '外卖食品', value: 'food' },
  { label: '文件资料', value: 'document' },
  { label: '生活用品', value: 'daily' },
  { label: '其他物品', value: 'other' }
];

const PICKUP_LOCATIONS = ['二期校园邮局', '一期丰巢', '一期妈妈驿站', '田径场'];
const DROPOFF_BUILDINGS = Array.from({ length: 20 }).map((_, idx) => `${idx + 1}栋`);
const TIME_RANGES = [
  { label: '上午(08:00-12:00)', value: 'morning' },
  { label: '下午(12:00-18:00)', value: 'afternoon' },
  { label: '晚上(18:00-22:00)', value: 'evening' }
];

Page({
  data: {
    itemTypeOptions: ITEM_TYPE_OPTIONS,
    pickupLocations: PICKUP_LOCATIONS,
    dropoffBuildings: DROPOFF_BUILDINGS,
    timeRanges: TIME_RANGES,
    selectedItemTypeIndex: null,
    selectedPickupIndex: null,
    selectedDropoffIndex: null,
    selectedRangeIndex: null,
    useTimeRange: true,
    submitting: false,
    autoPickupTip: '',
    form: {
      itemType: '',
      itemCount: '',
      itemDesc: '',
      pickupLocation: '',
      pickupCode: '',
      pickupRange: '',
      pickupTime: '',
      dropoffLocation: '',
      dropoffDetail: '',
      remark: '',
      totalPrice: ''
    }
  },

  onLoad() {
    this.prefillTemplate();
  },

  prefillTemplate() {
    const template = wx.getStorageSync('orderTemplate');
    if (!template) return;
    this.setData({
      form: {
        ...this.data.form,
        itemType: template.itemType || '',
        itemCount: template.itemCount || '',
        itemDesc: template.itemDesc || '',
        pickupLocation: template.pickupLocation || '',
        dropoffLocation: template.dropoffLocation || '',
        dropoffDetail: template.dropoffDetail || '',
        remark: template.note || '',
        totalPrice: template.estimatedPrice || ''
      },
      useTimeRange: !!template.pickupRange,
      selectedItemTypeIndex: template.itemType ? this.findOptionIndex(this.data.itemTypeOptions, template.itemType) : null,
      selectedPickupIndex: template.pickupLocation ? this.findOptionIndex(this.data.pickupLocations, template.pickupLocation) : null,
      selectedDropoffIndex: template.dropoffLocation ? this.findOptionIndex(this.data.dropoffBuildings, template.dropoffLocation) : null,
      selectedRangeIndex: template.pickupRange ? this.findOptionIndex(this.data.timeRanges.map(t => t.value), template.pickupRange) : null
    });
    wx.removeStorageSync('orderTemplate');
  },

  findOptionIndex(list, value) {
    if (!value) return null;
    return list.findIndex((item) => (item.value || item) === value);
  },

  onPickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = Number(e.detail.value);
    if (field === 'itemType') {
      this.setData({
        selectedItemTypeIndex: index,
        'form.itemType': this.data.itemTypeOptions[index].value
      });
    } else if (field === 'pickupLocation') {
      this.setData({
        selectedPickupIndex: index,
        'form.pickupLocation': this.data.pickupLocations[index]
      });
    } else if (field === 'dropoffLocation') {
      this.setData({
        selectedDropoffIndex: index,
        'form.dropoffLocation': this.data.dropoffBuildings[index]
      });
    } else if (field === 'pickupRange') {
      this.setData({
        selectedRangeIndex: index,
        'form.pickupRange': this.data.timeRanges[index].value
      });
    }
  },

  toggleTimeMode(e) {
    const mode = e.currentTarget.dataset.mode;
    this.setData({
      useTimeRange: mode === 'range'
    });
  },

  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      form: {
        ...this.data.form,
        [field]: e.detail.value
      }
    });
  },

  // 自动识别取件点：根据当前位置选择最近的校园取件点
  onAutoDetectPickup() {
    if (this.data.submitting) return;

    getUserLocation()
      .then(async ({ latitude, longitude }) => {
        try {
          const resp = await request({
            url: '/api/orders/campus/nearest',
            method: 'GET',
            data: {
              lat: latitude,
              lng: longitude,
              type: 'pickup_point'
            }
          });

          if (!resp || !resp.success || !resp.data) {
            wx.showToast({ title: '附近暂无取件点', icon: 'none' });
            return;
          }

          const loc = resp.data;
          const name = loc.name || '';
          const index = PICKUP_LOCATIONS.indexOf(name);

          // 如果距离值异常大（例如 > 5km），很可能是校园坐标仍为示意值，这时只提示“附近”避免误导
          let tip = `已自动匹配：${name}`;
          const d = typeof loc.distance_m === 'number' ? loc.distance_m : null;
          if (d !== null && d > 0 && d < 5000) {
            tip = `已自动匹配：${name}（约 ${d} 米）`;
          } else if (d !== null && d >= 5000) {
            tip = `已自动匹配：${name}（附近）`;
          }

          this.setData({
            selectedPickupIndex: index >= 0 ? index : this.data.selectedPickupIndex,
            'form.pickupLocation': name,
            autoPickupTip: tip
          });
        } catch (error) {
          console.error('自动识别取件点失败:', error);
          wx.showToast({ title: '获取附近取件点失败', icon: 'none' });
        }
      })
      .catch((err) => {
        console.error('获取定位失败:', err);
        wx.showToast({ title: '定位失败，请检查权限', icon: 'none' });
      });
  },

  async submitOrder(e) {
    if (this.data.submitting) return;

    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    const form = this.data.form;
    if (!form.pickupLocation) {
      wx.showToast({ title: '请选择取件地点', icon: 'none' });
      return;
    }
    if (!form.dropoffLocation) {
      wx.showToast({ title: '请选择送达地点', icon: 'none' });
      return;
    }
    if (!form.pickupCode) {
      wx.showToast({ title: '请输入取件码', icon: 'none' });
      return;
    }
    if (!form.totalPrice || isNaN(Number(form.totalPrice))) {
      wx.showToast({ title: '请输入订单金额', icon: 'none' });
      return;
    }

    const deliveryAddress = `${form.dropoffLocation}${form.dropoffDetail ? ` ${form.dropoffDetail.trim()}` : ''}`.trim();
    const deliveryTime = this.computeDeliveryTime(form.pickupRange, form.pickupTime);
    const rangeLabel = this.getRangeLabel(form.pickupRange);

    const noteParts = [form.remark, form.itemDesc, rangeLabel ? `期望时间段: ${rangeLabel}` : '']
      .filter(Boolean)
      .map((part) => part.trim())
      .filter(Boolean);

    const payload = {
      userId,
      pickup_location: form.pickupLocation,
      delivery_address: deliveryAddress,
      pickup_code: form.pickupCode,
      delivery_time: deliveryTime,
      suggested_fee: Number(form.totalPrice),
      note: noteParts.join('\n'),
      express_type: form.itemType || '',
      express_company: '其他',
      package_size: 'medium',
      item_count: form.itemCount || ''
    };

    this.setData({ submitting: true });
    wx.showLoading({ title: '提交中...' });

    try {
      const res = await request({
        url: '/api/orders',
        method: 'POST',
        data: payload
      });

      wx.hideLoading();
      this.setData({ submitting: false });

      if (res.success) {
        wx.showToast({ title: '下单成功', icon: 'success' });
        this.resetForm();
        setTimeout(() => {
          wx.navigateBack({ delta: 1 });
        }, 1200);
      } else {
        wx.showToast({ title: res.message || '提交失败', icon: 'none' });
      }
    } catch (error) {
      console.error('提交订单失败:', error);
      wx.hideLoading();
      this.setData({ submitting: false });
      wx.showToast({ title: '网络错误，请稍后再试', icon: 'none' });
    }
  },

  computeDeliveryTime(rangeValue, customTime) {
    if (this.data.useTimeRange && rangeValue) {
      const now = new Date();
      const pad = (num) => String(num).padStart(2, '0');
      const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
      if (rangeValue === 'morning') return `${date} 10:00:00`;
      if (rangeValue === 'afternoon') return `${date} 15:00:00`;
      if (rangeValue === 'evening') return `${date} 20:00:00`;
    }
    const normalized = this.normalizeDateTime(customTime);
    if (normalized) return normalized;
    const fallback = new Date(Date.now() + 60 * 60 * 1000);
    return this.formatDateTime(fallback);
  },

  normalizeDateTime(value) {
    if (!value) return null;
    let str = String(value).trim();
    if (!str) return null;
    if (str.includes('T')) str = str.replace('T', ' ');
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/.test(str)) {
      return `${str}:00`;
    }
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(str)) {
      return str;
    }
    return null;
  },

  getRangeLabel(rangeValue) {
    const item = this.data.timeRanges.find((t) => t.value === rangeValue);
    return item ? item.label : '';
  },

  formatDateTime(date) {
    const pad = (val) => String(val).padStart(2, '0');
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:00`;
  },

  resetForm() {
    this.setData({
      form: {
        itemType: '',
        itemCount: '',
        itemDesc: '',
        pickupLocation: '',
        pickupCode: '',
        pickupRange: '',
        pickupTime: '',
        dropoffLocation: '',
        dropoffDetail: '',
        remark: '',
        totalPrice: ''
      },
      selectedItemTypeIndex: null,
      selectedPickupIndex: null,
      selectedDropoffIndex: null,
      selectedRangeIndex: null,
      useTimeRange: true
    });
  }
});